<template>
  <div class="articcle-list">
    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
          v-for="(k, index) in list"
          :key="index"
          :article="k"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/user'
import ArticleItem from './article-item.vue'
export default {
  name: 'ArticleList',
  props: ['channel'],
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      error: false, // 控制数据加载结束
      timestamp: null, // 控制列表加载失败提示
      isreFreshLoading: false, // 控制下拉刷新
      refreshSuccessText: '刷新成功'
    }
  },
  methods: {
    // 初始化或滚动到底部的时候会触发调用 onLoad
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), // 请求劣势推荐传指定的时间戳
          with_top: 1
        })
        const { results } = data.data
        this.list.push(...results)

        this.loading = false

        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.loading = false // 关闭loading效果
        this.error = true // 开启错误提示
      }
      // 1. 请求获取数据

      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   // 2. 把请求结果数据放到 list 数组中
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1)
      //   }

      //   // 3. 本次数据加载结束之后要把加载状态设置为结束
      //   //     loading 关闭以后才能触发下一次的加载更多
      //   this.loading = false

      //   // 4. 判断数据是否全部加载完成
      //   if (this.list.length >= 40) {
      //     // 如果没有数据了，把 finished 设置为 true，之后不再触发加载更多
      //     this.finished = true
      //   }
      // }, 1000)
    },
    // 当下拉刷新的时候会触发调用该函数
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.unshift(...results)

        this.isreFreshLoading = false
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        this.refreshSuccessText = '刷新失败'
        this.isreFreshLoading = false
      }
    }
  },
  components: {
    ArticleItem
  },
  created () {
    console.log(this.list)
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
